import React from 'react';
import { connect } from 'react-redux'
import util from '../../util'
import cx from 'classnames'
import { bindActionCreators } from 'redux'
import * as okrAction from '../../actions/okr.action'
import { resetUser } from '../../actions/user.action'
import { resetTeam } from '../../actions/team.action'
import style from './style.objective-detail';
import { fetchAtList, clearAtList } from '../../actions/home.action'
import ObjectiveItem from './ObjectiveItem';
import ObjectiveCreate from './ObjectiveCreate';
import ObjectiveNote, { pageSize as commentsPageSize } from './ObjectiveNote';
import ObjectiveRelative from './ObjectiveRelative';
import { Link, LabelInput, Button } from 'sq-ui';
import { RadioGroup, Modal, info, error, success } from '../../ui-components';

import {
  createKeyResult,
  cancelRequestCreateItem,
  checkItemInput,
  requestEditObjective,
  requestEditKeyResult,
  cancelRequestEditItem,
  requestCreateKeyResult,
  updateObjective,
  updateKeyResult,
} from './Objective';

export default
@connect(({ okr, app }) => ({ okr, app }), dispatch => ({actions: bindActionCreators({...okrAction, resetUser, resetTeam, fetchAtList, clearAtList }, dispatch)}))
class ObjectiveTargetAudit extends React.Component {

  state = {
    // 审批类型，审批说明
    audit: "2",
    auditNotes: "",
    editItem: false,
    editObjective: false,
    editKeyResult: false,
    objective: null,
    keyResult: null,
    createItem: false,
    createObjective: false,
    createKeyResult: false,
    // 创建关键结果的目标Id
    objectiveId: null,
  };

  componentWillReceiveProps(props) {
    if (props.params.objectiveId != this.props.params.objectiveId) {
      this.props.actions.resetOkr();
      this.fetchContent(props);
    }
  }

  componentWillUnmount() {
    this.props.actions.resetUser();
    this.props.actions.resetTeam();
  }

  componentDidMount() {
    this.fetchContent();
  }

  // 查询要审核的结果
  fetchContent(props, excludeChildren, excludeAncester, refreshComments) {
    const { actions, params } = props || this.props;
    const { objectiveId } = params;
    const { keyResult } = this.props.location.query;
    // console.log(this.props);
    
    // 查询需要审批的结果
    actions.fetchObjectiveAudit(objectiveId, keyResult);
    // 更新目标
    // actions.fetchObjectiveDetail(objectiveId);
    /* if (!excludeAncester) {
      // 更新上级目标
      actions.fetchObjectiveAncester(objectiveId);
    }
    if (!excludeChildren) {
      // 更新下级目标
      actions.fetchObjectiveChildren(objectiveId);
    } */

    if (refreshComments) {
      this.refreshComments();
    }
  }

  // 刷新评论列表
  refreshComments(props) {
    const { actions, params } = props || this.props;
    const { objectiveId } = params;
    // actions.reFetchOkrComments(objectiveId, { pageSize: commentsPageSize, pageNumber: 1 });
  }

  // 刷新目标:
  //  评论
  //  目标对象
  //  上级目标
  refreshObjective(excludeAncester) {
    this.fetchContent(null, true, excludeAncester);
    this.refreshComments();
  }

  // 刷新关键结果
  //  评论
  //  关键结果对象
  refreshKeyResult() {
    // this.props.actions.fetchObjectiveDetail(this.props.params.objectiveId);
    this.refreshComments();
  }

  renderNav() {
    const { detail } = this.props.okr;
    if (util.isNull(detail)) return null;
    const { objectivePeriodName, objectivePeriodOwnerName } = detail;
    return (
      <div className={style.nav}>
        <Link to={`/okr?${util.body(this.props.location.query)}`} label={this.props.location.query.type == 1? '公司': objectivePeriodOwnerName}/>
        <Link
          className={style.period}
          label={objectivePeriodName}
          to={`/okr/${detail.objectivePeriodId}/objectives?${util.body(this.props.location.query)}`}
        />
      </div>
    );
  }

  // 提交审批
  handleSubmit = () => {
    let { audit, auditNotes } = this.state;
    const { objectiveId } = this.props.params;
    const { userId, keyResult } = this.props.location.query;

    auditNotes = auditNotes.trim();

    if(audit === "1" && auditNotes === ""){
      error("请填写重新考虑的审批说明");
      return;
    }
    
    info("提交中...");
    this.props.actions.createAuditKeyResult({audit, auditNotes, objectiveId, keyResult, userId}, () => {
      success("提交成功!");
      setTimeout(() => {
        this.props.history.push(`okr/objective-targetAll?userId=${userId}`);
      }, 1000)
    });
  }

  render() {
    const {
      detail,
      comments,
    } = this.props.okr;
    const {
      editable,
      objectivePeriodId,
    } = detail || {};
    return (
      <div>
        <div className={style['nav-bar']}>
          { this.renderNav() }
        </div>
        <div className={style.content}>
          <ObjectiveItem
            fetchContent={::this.fetchContent}
            editReamrk="false"
            objectiveCreatable={false}
            objectiveEditable={false}
            objectiveDeletable={false}
            editObjective={() => requestEditObjective.call(this, detail)}
            editKeyResult={requestEditKeyResult.bind(this)}
            requestCreateKeyResult={requestCreateKeyResult.bind(this)}
            editObjectiveDetail
            refreshObjective={::this.refreshObjective}
            refreshKeyResult={::this.refreshKeyResult}
            obj={detail}
            {...detail}
            {...this.props}
          />
        </div>
        <div className={style.auditBox}>
          <div className={style['auditType']}>
            <label htmlFor="agree">
              <input value="2" 
                    onClick={e => this.setState({audit: e.target.value})}
                    checked={this.state.audit === "2" ? true : false} 
                    type="radio" 
                    id="agree" 
                    name="auditType"/>
              <span>同意</span>
            </label>
            <label htmlFor="notAgree">
              <input value="1" 
                    onClick={e => this.setState({audit: e.target.value})}
                    checked={this.state.audit === "1" ? true : false} 
                    type="radio" 
                    id="notAgree" 
                    name="auditType"/>
              <span>请重新考虑</span>
            </label>
          </div>
          <div className={style.auditRemark}>
            <LabelInput
              onChange={e => this.setState({auditNotes: e.target.value})}
              value={this.setState.auditNotes}
              vertical
              label="审批说明"
              placeholder="请输入审批说明"
            />
          </div>
          <Button label="确定审批" onClick={this.handleSubmit} />
        </div>
      </div>
    );
  }
}
